<template>
  <div class="comment-container">
    <h3 class="legend">发表评论 --- {{ id }}</h3>
    <hr />
    <!-- 评论内容文本框 -->
    <textarea v-model="cmtinfo" maxlength="120" placeholder="请输入要吐槽的内容（最多120字）"></textarea>
    <!-- 发表评论按钮 -->
    <mt-button type="primary" size="large" class="btn-submit" @click="submitComment">发表评论</mt-button>
    <!-- 评论列表区域 -->
    <div class="cmt-list">
      <div v-for="(item, i) in cmtlist" :key="i" class="cmt-item">
        <div class="cmt-item-header">{{ item.user_name }} &nbsp; {{ item.add_time | dateFormat }}</div>
        <div class="cmt-item-body">{{ item.content }}</div>
      </div>
    </div>
    <!-- 加载更多评论 -->
    <mt-button type="danger" plain size="large" class="btn-submit" @click="getNextPage">加载更多</mt-button>
  </div>
</template>

<script>
import { Toast } from 'mint-ui'

export default {
  props: {
    id: {
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      // 当前请求的是第几页的数据
      page: 1,
      // 评论列表
      cmtlist: [],
      // 评论内容
      cmtinfo: ''
    }
  },
  mounted() {
    this.getCmtList()
  },
  methods: {
    // 获取评论列表数据
    async getCmtList() {
      const { data: res } = await this.$axios.get(`/api/getcomments/${this.id}?pageindex=${this.page}`)
      if (res.status === 0) {
        this.cmtlist = [...this.cmtlist, ...res.message]
      }
    },
    // 获取下一页的评论数据
    getNextPage() {
      this.page++
      this.getCmtList()
    },
    // 提交评论
    async submitComment() {
      // 判断内容是否为空
      if (this.cmtinfo.trim().length <= 0) {
        return Toast({
          message: '评论内容不能为空！',
          position: 'middle',
          duration: 1500
        })
      }
      // 发表评论
      const { data: res } = await this.$axios.post(`/api/postcomment/${this.id}`, { content: this.cmtinfo.trim() })
      if (res.status !== 0) {
        // 发表评论失败
        return Toast({
          message: '发表评论失败！',
          position: 'middle',
          duration: 1500
        })
      }
      // 发表评论成功
      Toast({
        message: '发表评论成功！',
        position: 'middle',
        duration: 1500
      })
      this.cmtlist.unshift({
        user_name: '匿名用户',
        add_time: new Date(),
        content: this.cmtinfo.trim()
      })
    }
  }
}
</script>

<style lang="less" scoped>
.comment-container {
  padding: 5px 0;
}
.legend {
  font-weight: bold;
  margin-bottom: 5px;
}
textarea {
  width: 100%;
  height: 60px;
  font-size: 13px;
  margin-top: 5px;
  resize: none;
}
.btn-submit {
  margin-top: 2px;
}
.cmt-list {
  padding-top: 5px;
}
.cmt-item {
  font-size: 12px;
}
.cmt-item-header {
  height: 30px;
  line-height: 30px;
  background-color: #eee;
}
.cmt-item-body {
  line-height: 30px;
  text-indent: 2em;
}
</style>
